#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

#define NUM 1024

//存放分割的指令和选项
char* g_argv[NUM];
//存放完整的指令和选项
char argv[NUM];

int main()
{
    while (1)
    {
        printf("[root@localhost]# ");
        fflush(stdout);

        memset(argv, '\0', sizeof argv);
        fgets(argv, sizeof argv, stdin);
        argv[strlen(argv) - 1] = '\0';
        
        int index = 1;
        g_argv[0] = strtok(argv, " ");
        if (strcmp(g_argv[0], "ls") == 0)
        {
            g_argv[index++] = "--color=auto";
        }
        if (strcmp(g_argv[0], "ll") == 0)
        {
            g_argv[0] = "ls";
            g_argv[index++] = "-l";
            g_argv[index++] = "--color=auto";
        }

        while ((g_argv[index++]) = strtok(NULL, " "));

        //内建命令，不执行子进程
        if (strcmp(g_argv[0], "cd") == 0)
        {
            if (g_argv[1] == NULL)
            {
                chdir("../");
            }
            else 
            {
                chdir(g_argv[1]); 
            }
            continue;
        }

        //创建子进程
        pid_t id = fork();
        if (id == 0)
        {
            //child
            execvp(g_argv[0], g_argv);
            printf("%s not find\n", g_argv[0]);
            exit(1);
        }
        else 
        {
            //father
            int status = 0;
            waitpid(id, &status, 0);

            if (WEXITED)
                printf("child process success, exit code: %d\n", WEXITSTATUS(status));
        }
    }

    return 0;
}
